/*
 * $Id: ClassLoaderUtils.java 154 2009-05-19 17:36:35Z meyer@alphatec.de $
 * 
 *
 * Copyright 2009 DeltaDesk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package deltadesk.core;

import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;

import org.java.plugin.Plugin;

/**
 * ClassLoaderUtils.
 * 
 * @author Andreas Meyer
 * @version $Revision: 154 $
 */
public class ClassLoaderUtils {

	/**
	 * Modify Java library path for locating native libraries.
	 * 
	 * @param plugin
	 * @param platform
	 */
	public static void addNativeLibraryPath(final Plugin plugin,
			                                final String platform) {
		
		final String path = resolvePath(plugin, platform);

		final Class<ClassLoader> clClass = ClassLoader.class;
		final Field field;
		try {
			field = clClass.getDeclaredField("sys_paths");
			final boolean accessible = field.isAccessible();
			if (!accessible) {
				field.setAccessible(true);
			}
//			final Object original = field.get(clClass);
			field.set(clClass, null);
			System.setProperty("java.library.path", path);
//			field.set(clClass, original);
			field.setAccessible(accessible);
		} catch (final Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * Resolve the directory that contains the native libraries for
	 * a specified plugin and platform.
	 * 
	 * @param p
	 * @param platform
	 * @return
	 */
	private static String resolvePath(final Plugin p, final String platform) {
		
		final URL loc = p.getDescriptor().getLocation();
		final File dir = new File(loc.getFile()).getParentFile();
		final File libDir = new File(dir, "lib" + File.separator + "native"
				+ File.separator + platform);
		
		return libDir.toString();
	}
}
